package portal.web.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import portal.facade.PortalComprasFacadeStateful;
import portal.vo.ItemVO;
import portal.vo.ProductoVO;
import portal.web.businessDelegate.PortalComprasDelegate;

@SuppressWarnings("serial")
public class AgregarACarritoServlet extends HttpServlet {

	private static Logger logger = Logger.getLogger(AgregarACarritoServlet.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		processRequest(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		processRequest(req, resp);
	}

	private void processRequest(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>AgregarACarritoServlet<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
		HttpSession session = req.getSession(true);
		Long idProducto = Long.parseLong((String)req.getParameter("id"));
		
		logger.debug("Id:" + idProducto);
		
		PortalComprasFacadeStateful facadeStateful = (PortalComprasFacadeStateful) session.getAttribute("facadeStateful");
		
		// primero busco el producto en el carrito
		ItemVO item = facadeStateful.buscarItem(idProducto);
		
		if(item != null) { //el item existe en el carrito
			facadeStateful.actualizarCantidadItem(idProducto, 1);
			System.out.println("****cantidad: " + item.getCantidad());
		} else { //el item no existe en el carrito
			ProductoVO producto = PortalComprasDelegate.getInstance().getProductoById(idProducto);
			ItemVO itemNuevo = new ItemVO();
			itemNuevo.setItemProducto(producto);
			itemNuevo.setCantidad(1);
			facadeStateful.agregarItem(itemNuevo);
			
		}
		
		req.setAttribute("listaCarrito", facadeStateful.getListaItems());
		
		logger.debug("Size:" + facadeStateful.getListaItems().size());
		
		req.getRequestDispatcher("/jsp/carritoCompras.jsp").forward(req, resp);

	}
}
